<?php

# http://projects:8081/cdapp-2kt-api/api/utils_general_report.php

include_once '_portal.php';

$startTime   = $post->startTime ?? date('Y-m-01 00:00:00');
$endTime     = $post->endTime ?? date('Y-m-d H:i:s');
$hourDispose = $post->endTime ?? 40;

define("START_TIME", $startTime);
define("END_TIME", $endTime);
define("HOUR_DISPOSE", $hourDispose);

main();
function main() {
  $flow_brief   = get_flow_brief();
  $sector_brief = get_sector_brief();
  $hour_brief   = get_hour_brief();

  $val_all       = $flow_brief['Total'] ?? 0;
  $user_count    = $hour_brief['memberCount'] ?? 1;
  $user_count_2  = $hour_brief['memberCount2'] ?? 1;
  $sector_hours  = $sector_brief['sectorHours'] ?? 1;
  $capita_flow   = get_capita_flow($val_all, $user_count);
  $capita_flow_2 = get_capita_flow($val_all, $user_count_2);
  $sector_flow   = get_sector_flow($val_all, $sector_hours);

  output(['startTime' => START_TIME, 'endTime' => END_TIME, 'flow' => $flow_brief, 'sector' => $sector_brief, 'hour' => $hour_brief, 'capitaFlow' => $capita_flow, 'capitaFlow2' => $capita_flow_2, 'sectorFlow' => $sector_flow]);
}

function get_flow_brief() {
  $start_time = START_TIME;
  $end_time   = END_TIME;
  $sql        = "SELECT `moment`,`content`,`sector`,`mode` FROM `2kt_flow_record` WHERE `moment` >= '{$start_time}' AND `moment` <= '{$end_time}'";
  $data       = exec_sql($sql);
  if (! $data || ! is_array($data) || ! count($data)) {
    return [];
  }
  $tags = explode(':', get_param('NTFM_TMA_PAYLOAD_LAST')['key']);

  $val_zuuu   = 0;
  $val_zutf   = 0;
  $val_misc   = 0;
  $val_all    = 0;
  $line_count = 0;
  for ($i = 0; $i < count($tags); $i++) {
    $tag = $tags[$i];
    for ($j = 0; $j < count($data); $j++) {
      $line    = $data[$j];
      $content = json_decode($line['content']);
      // if (count($content) != count($tags)) {
      //   return ['moment' => $line['moment']];
      // }
      $line_count++;
      $val = (int)$content[$i];
      if (strstr($tag, 'ZUUU')) {
        $val_zuuu += $val;
      } elseif (strstr($tag, 'ZUTF')) {
        $val_zutf += $val;
      } else {
        $val_misc += $val;
      }
      $val_all += $val;
    }
  }

  return ['ZUUU' => $val_zuuu, 'ZUTF' => $val_zutf, 'Misc' => $val_misc, 'Total' => $val_all];
}

function get_sector_brief() {
  $start_time = START_TIME;
  $end_time   = END_TIME;
  $sql        = "SELECT `startTime`,`endTime`,`count` FROM `2kt_sector_record` WHERE `endTime` >= '{$start_time}' AND `startTime` <= '{$end_time}'";
  $data       = exec_sql($sql);
  if (! $data || ! is_array($data) || ! count($data)) {
    return [];
  }
  $hours      = 0;
  $range_from = strtotime(START_TIME);
  $range_to   = strtotime(END_TIME);
  foreach ($data as $row) {
    $start = strtotime($row['startTime']);
    $end   = strtotime($row['endTime']);
    $start = $start > $range_from ? $start : $range_from;
    $end   = $end < $range_to ? $end : $range_to;
    $hours += (int)$row['count'] * ($end - $start) / 3600;
  }
  $hours = round($hours, 0);
  return ['sectorHours' => $hours];
}

function get_hour_brief() {
  $start_time = START_TIME;
  $end_time   = END_TIME;
  $sql        = "SELECT `recordId`,`userName`,`userId`,`startTime`,`endTime` FROM `2kt_seat_hours` WHERE `endTime` >= '{$start_time}' AND `startTime` <= '{$end_time}' AND `seatRoleId` != 3";
  $data       = exec_sql($sql);
  if (! $data || ! is_array($data) || ! count($data)) {
    return [];
  }
  $hours      = 0;
  $range_from = strtotime(START_TIME);
  $range_to   = strtotime(END_TIME);
  $user_hours = [];
  foreach ($data as $row) {
    $user     = 'u' . $row['userId'];
    $start    = strtotime($row['startTime']);
    $end      = strtotime($row['endTime']);
    $start    = $start > $range_from ? $start : $range_from;
    $end      = $end < $range_to ? $end : $range_to;
    $duration = ($end - $start) / 3600;
    $hours += $duration;
    if (array_key_exists($user, $user_hours)) {
      $user_hours[$user] += $duration;
    } else {
      $user_hours[$user] = $duration;
    }
  }

  // 统计打卡总人数、>=40人数

  $user_count   = 0;
  $user_count_2 = 0;

  foreach ($user_hours as $hour_u) {
    $user_count++;
    if ($hour_u >= HOUR_DISPOSE) {
      $user_count_2++;
    }
  }

  $hour_avg   = $hours / $user_count;
  $hour_avg   = round($hour_avg, 0);
  $hours      = round($hours, 0);
  $hour_avg_2 = $hours / $user_count_2;
  $hour_avg_2 = round($hour_avg_2, 0);

  return [
    'totalHours'      => $hours,
    'hoursPerCapita'  => $hour_avg,
    'memberCount'     => $user_count,
    'hoursPerCapita2' => $hour_avg_2,
    'memberCount2'    => $user_count_2,
  ];
}

function get_capita_flow($val_all, $user_count) {
  if (is_numeric($val_all) && is_numeric($user_count)) {
    $val = $val_all / $user_count;
    $val = round($val, 0);
    return ['flowPerCapita' => $val];
  } else {
    return [];
  }
}

function get_sector_flow($val_all, $sector_hours) {
  if (is_numeric($val_all) && is_numeric($sector_hours)) {
    $val = $val_all / $sector_hours;
    $val = round($val, 0);
    return ['flowPerSector' => $val];
  } else {
    return [];
  }
}